
<!DOCTYPE html>
<html lang="">


<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">
  <meta name="theme-color" content="#202020">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <script src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" async></script>
  
  
    <meta name="keywords" content>
  

  
    <meta name="description" content="Jwt的介绍">
  
  
  
  <link rel="icon" type="image/x-icon" href="/images/footer-logo.png">
  
  <title>Jwt的介绍 [ 51AIOps 专注于运维自动化  微信： kaipython ]</title>
  
    <!-- stylesheets list from config.yml -->
    
      <link rel="stylesheet" href="//cdn.bootcss.com/pure/1.0.0/pure-min.css">
    
      <link rel="stylesheet" href="/css/xoxo.css">
    
  
</head>


<body>
  <div class="nav-container">
    <nav class="home-menu pure-menu pure-menu-horizontal">
  <a class="pure-menu-heading" href="/">
    
    <span class="title" style="text-transform:none">51AIOps 专注于运维自动化  微信： kaipython</span>
  </a>

  <ul class="pure-menu-list clearfix">
      
          
            
              <li class="pure-menu-item"><a href="/" class="pure-menu-link">首页</a></li>
            
          
      
  </ul>
   
</nav>

  </div>

  <div class="container" id="content-outer">
    <div class="inner" id="content-inner" style='margin-left:-68px!important'>
      <div class="post-container">
  <article class="post" id="post">
    <header class="post-header text-center">
      <h1 class="title">
        Jwt的介绍
      </h1>
      <span>
        
        <time class="time" datetime="2020-06-06T16:00:00.000Z">
        2020-06-07
      </time>
        
      </span>
      <span class="slash">/</span>
      <span class="post-meta">
      <span class="post-tags">
        
      </span>
    </span>
      <span class="slash">/</span>
      <span class="read">
      <span id="busuanzi_value_page_pv"></span> 点击
    </span>
      <span class="slash">/</span>
    </header>

    <div class="post-content">
      <p>jwt（JSON Web Tokens），是一种开发的行业标准 <a href="https://tools.ietf.org/html/rfc7519" target="_blank" rel="noopener">RFC 7519</a> ，用于安全的表示双方之间的声明。目前，jwt广泛应用在系统的用户认证方面，特别是现在前后端分离项目。</p>
<h2 id="1-jwt认证流程"><a href="#1-jwt认证流程" class="headerlink" title="1. jwt认证流程"></a>1. jwt认证流程</h2><p><img src="https://pythonav.com/media/uploads/2019/11/14/image-20191112150846485.png" alt="img"></p>
<p>在项目开发中，一般会按照上图所示的过程进行认证，即：用户登录成功之后，服务端给用户浏览器返回一个token，以后用户浏览器要携带token再去向服务端发送请求，服务端校验token的合法性，合法则给用户看数据，否则，返回一些错误信息。</p>
<p>传统token方式和jwt在认证方面有什么差异？</p>
<ul>
<li><p>传统token方式</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">用户登录成功后，服务端生成一个随机token给用户，并且在服务端(数据库或缓存)中保存一份token，以后用户再来访问时需携带token，服务端接收到token之后，去数据库或缓存中进行校验token的是否超时、是否合法。</span><br></pre></td></tr></table></figure>
</li>
<li><p>jwt方式</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">用户登录成功后，服务端通过jwt生成一个随机token给用户（服务端无需保留token），以后用户再来访问时需携带token，服务端接收到token之后，通过jwt对token进行校验是否超时、是否合法。</span><br></pre></td></tr></table></figure>

</li>
</ul>
<p>想要连接JWT的原理，推荐大家阅读：<a href="https://www.ruanyifeng.com/blog/2018/07/json_web_token-tutorial.html" target="_blank" rel="noopener">阮一峰的JWT入门教程</a></p>
<h2 id="2-jwt创建token"><a href="#2-jwt创建token" class="headerlink" title="2. jwt创建token"></a>2. jwt创建token</h2><h3 id="2-1-原理"><a href="#2-1-原理" class="headerlink" title="2.1 原理"></a>2.1 原理</h3><p>jwt的生成token格式如下，即：由 <code>.</code> 连接的三段字符串组成。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c</span><br></pre></td></tr></table></figure>

<p>生成规则如下：</p>
<ul>
<li><p>第一段HEADER部分，固定包含算法和token类型，对此json进行base64url加密，这就是token的第一段。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#123;  &quot;alg&quot;: &quot;HS256&quot;,  &quot;typ&quot;: &quot;JWT&quot;&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>第二段PAYLOAD部分，包含一些数据，对此json进行base64url加密，这就是token的第二段。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#123;  &quot;sub&quot;: &quot;1234567890&quot;,  &quot;name&quot;: &quot;John Doe&quot;,  &quot;iat&quot;: 1516239022  ...&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>第三段SIGNATURE部分，把前两段的base密文通过<code>.</code>拼接起来，然后对其进行<code>HS256</code>加密，再然后对<code>hs256</code>密文进行base64url加密，最终得到token的第三段。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">base64url(    HMACSHA256(      base64UrlEncode(header) + &quot;.&quot; + base64UrlEncode(payload),      your-256-bit-secret (秘钥加盐)    ))</span><br></pre></td></tr></table></figure>

</li>
</ul>
<p>最后将三段字符串通过 <code>.</code>拼接起来就生成了jwt的token。</p>
<p><strong>注意</strong>：base64url加密是先做base64加密，然后再将 <code>-</code> 替代 <code>+</code> 及 <code>_</code> 替代 <code>/</code> 。</p>
<h3 id="2-2-代码实现"><a href="#2-2-代码实现" class="headerlink" title="2.2 代码实现"></a>2.2 代码实现</h3><p>基于Python的pyjwt模块创建jwt的token。</p>
<ul>
<li><p>安装</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pip3 install pyjwt</span><br></pre></td></tr></table></figure>
</li>
<li><p>实现</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> jwt</span><br><span class="line"><span class="keyword">import</span> datetime</span><br><span class="line"><span class="keyword">from</span> jwt <span class="keyword">import</span> exceptions</span><br><span class="line">SALT = <span class="string">'iv%x6xo7l7_u9bf_u!9#g#m*)*=ej@bek5)(@u3kh*72+unjv='</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">create_token</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="comment"># 构造header</span></span><br><span class="line">    headers = &#123;</span><br><span class="line">        <span class="string">'typ'</span>: <span class="string">'jwt'</span>,</span><br><span class="line">        <span class="string">'alg'</span>: <span class="string">'HS256'</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment"># 构造payload</span></span><br><span class="line">    payload = &#123;</span><br><span class="line">        <span class="string">'user_id'</span>: <span class="number">1</span>, <span class="comment"># 自定义用户ID</span></span><br><span class="line">        <span class="string">'username'</span>: <span class="string">'wupeiqi'</span>, <span class="comment"># 自定义用户名</span></span><br><span class="line">        <span class="string">'exp'</span>: datetime.datetime.utcnow() + datetime.timedelta(minutes=<span class="number">5</span>) <span class="comment"># 超时时间</span></span><br><span class="line">    &#125;</span><br><span class="line">    result = jwt.encode(payload=payload, key=SALT, algorithm=<span class="string">"HS256"</span>, headers=headers).decode(<span class="string">'utf-8'</span>)</span><br><span class="line">    <span class="keyword">return</span> result</span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">    token = create_token()</span><br><span class="line">    print(token)</span><br></pre></td></tr></table></figure>



</li>
</ul>
<h2 id="3-jwt校验token"><a href="#3-jwt校验token" class="headerlink" title="3. jwt校验token"></a>3. jwt校验token</h2><p>一般在认证成功后，把jwt生成的token返回给用户，以后用户再次访问时候需要携带token，此时jwt需要对token进行<code>超时</code>及<code>合法性</code>校验。</p>
<p>获取token之后，会按照以下步骤进行校验：</p>
<ul>
<li><p>将token分割成 <code>header_segment</code>、<code>payload_segment</code>、<code>crypto_segment</code> 三部分</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">jwt_token = <span class="string">"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"</span>signing_input, crypto_segment = jwt_token.rsplit(<span class="string">b'.'</span>, <span class="number">1</span>)</span><br><span class="line">header_segment, payload_segment = signing_input.split(<span class="string">b'.'</span>, <span class="number">1</span>)</span><br></pre></td></tr></table></figure>
</li>
<li><p>对第一部分<code>header_segment</code>进行base64url解密，得到<code>header</code></p>
</li>
<li><p>对第二部分<code>payload_segment</code>进行base64url解密，得到<code>payload</code></p>
</li>
<li><p>对第三部分<code>crypto_segment</code>进行base64url解密，得到<code>signature</code></p>
</li>
<li><p>对第三部分<code>signature</code>部分数据进行合法性校验</p>
<ul>
<li>拼接前两段密文，即：<code>signing_input</code></li>
<li>从第一段明文中获取加密算法，默认：<code>HS256</code></li>
<li>使用 算法+盐 对<code>signing_input</code> 进行加密，将得到的结果和<code>signature</code>密文进行比较。</li>
</ul>
</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> jwt</span><br><span class="line"><span class="keyword">import</span> datetime</span><br><span class="line"><span class="keyword">from</span> jwt <span class="keyword">import</span> exceptions</span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">get_payload</span><span class="params">(token)</span>:</span></span><br><span class="line">    <span class="string">"""</span></span><br><span class="line"><span class="string">    根据token获取payload</span></span><br><span class="line"><span class="string">    :param token:</span></span><br><span class="line"><span class="string">    :return:</span></span><br><span class="line"><span class="string">    """</span></span><br><span class="line">    <span class="keyword">try</span>:</span><br><span class="line">        <span class="comment"># 从token中获取payload【不校验合法性】</span></span><br><span class="line">        <span class="comment"># unverified_payload = jwt.decode(token, None, False)</span></span><br><span class="line">        <span class="comment"># print(unverified_payload)</span></span><br><span class="line">        <span class="comment"># 从token中获取payload【校验合法性】</span></span><br><span class="line">        verified_payload = jwt.decode(token, SALT, <span class="literal">True</span>)</span><br><span class="line">        <span class="keyword">return</span> verified_payload</span><br><span class="line">    <span class="keyword">except</span> exceptions.ExpiredSignatureError:</span><br><span class="line">        print(<span class="string">'token已失效'</span>)</span><br><span class="line">    <span class="keyword">except</span> jwt.DecodeError:</span><br><span class="line">        print(<span class="string">'token认证失败'</span>)</span><br><span class="line">    <span class="keyword">except</span> jwt.InvalidTokenError:</span><br><span class="line">        print(<span class="string">'非法的token'</span>)</span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">    token = <span class="string">"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NzM1NTU1NzksInVzZXJuYW1lIjoid3VwZWlxaSIsInVzZXJfaWQiOjF9.xj-7qSts6Yg5Ui55-aUOHJS4KSaeLq5weXMui2IIEJU"</span></span><br><span class="line">    payload = get_payload(token)</span><br></pre></td></tr></table></figure>

<h2 id="4-jwt实战"><a href="#4-jwt实战" class="headerlink" title="4. jwt实战"></a>4. jwt实战</h2><h3 id="4-1-django-案例"><a href="#4-1-django-案例" class="headerlink" title="4.1 django 案例"></a>4.1 django 案例</h3><p>在用户登录成功之后，生成token并返回，用户再次来访问时需携带token。</p>
<p>此示例在django的中间件中对tokne进行校验，内部编写了两个中间件来支持用户通过两种方式传递token。</p>
<ul>
<li><p><code>url</code>传参</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">http://127.0.0.1/?token=eyJhbGciOiJIUzI1N...</span><br></pre></td></tr></table></figure>

<p><img src="https://pythonav.com/media/uploads/2019/11/14/image-20191114053221220.png" alt="img"></p>
</li>
<li><p><code>Authorization</code>请求头</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">GET /something/ HTTP/1.1</span><br><span class="line">Host: lupython.com</span><br><span class="line">Authorization: JWT eyJhbGciOiAiSFMyNTYiLCAidHlwIj</span><br></pre></td></tr></table></figure>

<p><img src="https://pythonav.com/media/uploads/2019/11/14/image-20191114053403797.png" alt="img"></p>
</li>
</ul>
<p>源码下载：<a href="https://pan.baidu.com/s/1ANibEXYocu6V1JfDUydRHw" target="_blank" rel="noopener">https://pan.baidu.com/s/1ANibEXYocu6V1JfDUydRHw</a></p>

    </div>

  </article>
  <div class="toc-container">
    
  <div id="toc" class="toc-article">
    <strong class="toc-title">目录</strong>
    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-jwt认证流程"><span class="toc-text">1. jwt认证流程</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-jwt创建token"><span class="toc-text">2. jwt创建token</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#2-1-原理"><span class="toc-text">2.1 原理</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2-代码实现"><span class="toc-text">2.2 代码实现</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-jwt校验token"><span class="toc-text">3. jwt校验token</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-jwt实战"><span class="toc-text">4. jwt实战</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#4-1-django-案例"><span class="toc-text">4.1 django 案例</span></a></li></ol></li></ol>
  </div>


  </div>
</div>
<script type="text/javascript" src="//rf.revolvermaps.com/0/0/8.js?i=5sr5du46f27&amp;m=0&amp;c=ff0000&amp;cr1=ffffff&amp;f=arial&amp;l=33" async="async"></script>
<div class="copyright">
    <span>本作品采用</span>
    <a href="https://creativecommons.org/licenses/by/4.0/">知识共享署名 4.0 国际许可协议</a>
    <span>进行许可。 转载时请注明原文链接。</span>
</div>


  
    <div class="post-nav" style="margin-left:-168px;">
      <div class="post-nav-item post-nav-next">
        
          <span>〈 </span>
          <a href="/2020/05/04/Gin框架学习/" rel="next" title="Gin框架学习">
          Gin框架学习
          </a>
        
      </div>
  
      <div class="post-nav-item post-nav-prev">
          
          <a href="/2020/06/09/稳定性实践：容量规划之压测系统建设/" rel="prev" title="稳定性实践：容量规划之压测系统建设">
            稳定性实践：容量规划之压测系统建设
          </a>
          <span>〉</span>
        
      </div>
    </div>
  


	
	<div style="width:109%; margin-left:-144px" id="lv-container" data-id="city" data-uid="MTAyMC80OTg5NS8yNjM4Ng==">
	<script type="text/javascript">
   	   (function(d, s) {
       		var j, e = d.getElementsByTagName(s)[0];

       		if (typeof LivereTower === 'function') { return; }

       		j = d.createElement(s);
       		j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
       		j.async = true;

       		e.parentNode.insertBefore(j, e);
   	   })(document, 'script');
	</script>
	<noscript> 为正常使用来必力评论功能请激活JavaScript</noscript>
        </div>
	



    </div>

    

  </div>
  <footer class="footer text-center">
    <div id="bottom-inner">
        <a class="bottom-item" href target="_blank">GitHub</a> |
        <a class="bottom-item" href>友情链接</a> |
        <a class="bottom-item" href="https://hexo.io" target="_blank">Powered by hexo</a> |
        <a class="bottom-item" href="https://github.com/fooying/hexo-theme-xoxo-plus" target="_blank">Theme xoxo-plus</a> |
        <a class="bottom-item" href="/atom.xml">订阅</a>
    </div>
</footer>

  

<script>
  (function(window, document, undefined) {

    var timer = null;

    function returnTop() {
      cancelAnimationFrame(timer);
      timer = requestAnimationFrame(function fn() {
        var oTop = document.body.scrollTop || document.documentElement.scrollTop;
        if (oTop > 0) {
          document.body.scrollTop = document.documentElement.scrollTop = oTop - 50;
          timer = requestAnimationFrame(fn);
        } else {
          cancelAnimationFrame(timer);
        }
      });
    }

    var hearts = [];
    window.requestAnimationFrame = (function() {
      return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(callback) {
          setTimeout(callback, 1000 / 60);
        }
    })();
    init();

    function init() {
      css(".heart{z-index:9999;width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: absolute;}.heart:after{top: -5px;}.heart:before{left: -5px;}");
      attachEvent();
      gameloop();
      addMenuEvent();
    }

    function gameloop() {
      for (var i = 0; i < hearts.length; i++) {
        if (hearts[i].alpha <= 0) {
          document.body.removeChild(hearts[i].el);
          hearts.splice(i, 1);
          continue;
        }
        hearts[i].y--;
        hearts[i].scale += 0.004;
        hearts[i].alpha -= 0.013;
        hearts[i].el.style.cssText = "left:" + hearts[i].x + "px;top:" + hearts[i].y + "px;opacity:" + hearts[i].alpha + ";transform:scale(" + hearts[i].scale + "," + hearts[i].scale + ") rotate(45deg);background:" + hearts[i].color;
      }
      requestAnimationFrame(gameloop);
    }

    /**
     * 给logo设置点击事件
     * 
     * - 回到顶部
     * - 出现爱心
     */
    function attachEvent() {
      var old = typeof window.onclick === "function" && window.onclick;
      var logo = document.getElementById("logo");
      if (logo) {
        logo.onclick = function(event) {
          returnTop();
          old && old();
          createHeart(event);
        }
      }
      
    }

    function createHeart(event) {
      var d = document.createElement("div");
      d.className = "heart";
      hearts.push({
        el: d,
        x: event.clientX - 5,
        y: event.clientY - 5,
        scale: 1,
        alpha: 1,
        color: randomColor()
      });
      document.body.appendChild(d);
    }

    function css(css) {
      var style = document.createElement("style");
      style.type = "text/css";
      try {
        style.appendChild(document.createTextNode(css));
      } catch (ex) {
        style.styleSheet.cssText = css;
      }
      document.getElementsByTagName('head')[0].appendChild(style);
    }

    function randomColor() {
      // return "rgb(" + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + ")";
      return "#F44336";
    }

    function addMenuEvent() {
      var menu = document.getElementById('menu-main-post');
      if (menu) {
        var toc = document.getElementById('toc');
        if (toc) {
          menu.onclick = function() {
            if (toc) {
              if (toc.style.display == 'block') {
                toc.style.display = 'none';
              } else {
                toc.style.display = 'block';
              }
            }
          };
        } else {
          menu.style.display = 'none';
        }
      }
    }

  })(window, document);
</script>

  



  

</body>
</html>
